<?php

namespace App\Http\Controllers\Api\Promotion;

use Illuminate\Http\Request;

use App\Http\Controllers\Controller;

use App\Models\Promotion\Seckill;

use Illuminate\Support\Facades\Redis as Redis;

class SeckillController extends Controller
{

    /**
     * 秒杀列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function init(Request $request){

        $id = $request->input('id');

        if (!ebsig_is_int($id)) {
            return response()->json(['code' => 10000, 'message' => '缺少参数：id']);
        }

        //获取秒杀信息
        $second = Seckill::getCache($id);
        if (!$second || $second['useFlg'] == 0) {
            return response()->json(['code' => 10001, 'message' => '秒杀不存在']);
        }

        if ($second['end_date'] < date('Y-m-d')) {
            return response()->json(['code' => 10002, 'message' => '秒杀已过期']);

        }

        //获取秒杀时间段信息
        if (!$second['goods']) {
            return response()->json(['code' => 10003, 'message' => '秒杀时间段不存在']);
        }

        foreach ($second['goods'] as &$t) {
            foreach ($t['list'] as $k => &$g) {
                if ($g['useFlg'] == 0) {
                    unset($t['list'][$k]);
                    continue;
                }

                //秒杀已购数量
                $saled_amount = Redis::get('SEC_KILL_BUY_NUM_' . $id . '_' . $t['time_slot_id'] . '_' . $g['postID']);
                $g['saled_amount'] = $saled_amount;
                //购买进度比例
                $g['buy_progress'] = number_format($saled_amount / $g['max_sale_amount'], 2) * 100;

                //是否有库存: 0.有  1.无
                $end_buy = 0;
                if ($saled_amount >= $g['max_sale_amount']) {
                    $end_buy = 1;
                }
                $g['end_buy'] = $end_buy;
            }
        }


        if (isset($second['advert']) && !empty($second['advert'])) {
            $host = $request->getSchemeAndHttpHost();
            foreach ($second['advert'] as &$item) {
                $item['photo_url'] = $host . $item['photo_url'];
            }
        }

        return response()->json(['code' => 200, 'message' => 'ok', 'data' => $second]);

    }

}